﻿using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace YouDaoNotesCodes.JSON
{
    class JsonApplication
    {
        /// <summary>
        /// 按照JSON串中某个key值对应的Value进行排序-->做法：转为实体类、利用 Newtonsoft.Json排序
        /// </summary>
        public static void sortJSON()
        {
            string j1 = "[{\"id\":\"1001\",name:\"a\"},{\"id\":\"1006\",\"name\":\"b\"},{\"id\":\"1003\",\"name\":\"c\"},{\"id\":\"1007\",\"name\":\"g\"},{\"id\":\"1005\",\"name\":\"df\"},{\"id\":\"1009\",\"name\":\"dfg\"}]";

            List<Test> dataList = JsonConvert.DeserializeObject<List<Test>>(j1);
            dataList = dataList.OrderBy(p => p.id).ToList();

            foreach (Test t in dataList)
            {
                if (t.id==1001)
                {
                    t.name = "gnplums";//直接赋值更改节点值
                }         
            }
            string result = JsonConvert.SerializeObject(dataList);

            Console.WriteLine(result);
            Console.ReadKey();
        }
    }
    /// <summary>
    /// 测试JSON排序
    /// </summary>
    public class Test
    {
        public int id { set; get; }
        public string name { set; get; }
    }
}
